/**
 * 格式化工具函数
 */

/**
 * 格式化日期
 * @param date 日期
 * @param format 格式，默认'YYYY-MM-DD'
 * @returns 格式化后的日期字符串
 */
export const formatDate = (date: Date | string | number, format: string = 'YYYY-MM-DD'): string => {
  const d = date instanceof Date ? date : new Date(date);
  
  if (isNaN(d.getTime())) {
    return '';
  }
  
  const year = d.getFullYear();
  const month = d.getMonth() + 1;
  const day = d.getDate();
  const hours = d.getHours();
  const minutes = d.getMinutes();
  const seconds = d.getSeconds();
  
  return format
    .replace('YYYY', year.toString())
    .replace('MM', month < 10 ? `0${month}` : month.toString())
    .replace('DD', day < 10 ? `0${day}` : day.toString())
    .replace('HH', hours < 10 ? `0${hours}` : hours.toString())
    .replace('mm', minutes < 10 ? `0${minutes}` : minutes.toString())
    .replace('ss', seconds < 10 ? `0${seconds}` : seconds.toString());
};

/**
 * 格式化金额
 * @param amount 金额
 * @param decimals 小数位数，默认2
 * @param decimalSeparator 小数点符号，默认'.'
 * @param thousandsSeparator 千分位符号，默认','
 * @returns 格式化后的金额字符串
 */
export const formatMoney = (
  amount: number | string,
  decimals: number = 2,
  decimalSeparator: string = '.',
  thousandsSeparator: string = ','
): string => {
  const number = Number(amount);
  
  if (isNaN(number)) {
    return '';
  }
  
  const fixed = number.toFixed(decimals);
  const [integerPart, decimalPart] = fixed.split('.');
  
  const formattedIntegerPart = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, thousandsSeparator);
  
  return decimalPart
    ? `${formattedIntegerPart}${decimalSeparator}${decimalPart}`
    : formattedIntegerPart;
};

/**
 * 格式化手机号码
 * @param phone 手机号码
 * @returns 格式化后的手机号码
 */
export const formatPhone = (phone: string): string => {
  const cleaned = phone.replace(/\D/g, '');
  
  if (cleaned.length !== 11) {
    return phone;
  }
  
  return `${cleaned.substring(0, 3)} ${cleaned.substring(3, 7)} ${cleaned.substring(7, 11)}`;
}; 